﻿using HandyControl.Controls;
using HandyControl.Themes;
using log4net;
using PlaceOrder_Admin.ViewModels;
using PlaceOrder_Admin.Views;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Input;
using Application = System.Windows.Application;

namespace PlaceOrder_Admin
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(App));
        private static Mutex mutex;

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {

            // Register log4net logger instance
            containerRegistry.RegisterInstance(log);

            // Register other types
            containerRegistry.Register<ILoginService, LoginService>();

            containerRegistry.RegisterSingleton<IUserHelper, UserHelper>();
            containerRegistry.RegisterSingleton<IDataHelper, DataHelper>();
            containerRegistry.RegisterSingleton<IDatabase, Database>();
            containerRegistry.RegisterSingleton<IDailyData, DailyData>();
            containerRegistry.RegisterSingleton<IData, Data>();

            containerRegistry.RegisterSingleton<ChatAdminMessageViewModel>();
            containerRegistry.Register<ChatAdminWindow>();


            containerRegistry.RegisterDialog<LoginView, LoginViewModel>();
            containerRegistry.RegisterForNavigation<IndexAdminView, IndexAdminViewModel>();
            containerRegistry.RegisterForNavigation<ReviewView, ReviewViewModel>();
            containerRegistry.RegisterForNavigation<ChatAdminMessageView, ChatAdminMessageViewModel>();





            ///多个实例
            containerRegistry.RegisterMany<ChatAdminWindowViewModel>();
        }

        protected override System.Windows.Window CreateShell()
        {
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
            AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
            return ContainerLocator.Container.Resolve<MainView>();
        }

        protected override void OnInitialized()
        {
            var dialog = ContainerLocator.Container.Resolve<IDialogService>();
            dialog.ShowDialog("LoginView", callback =>
            {
                if (callback.Result != ButtonResult.OK)
                {
                    Environment.Exit(0);
                    return;
                }

                if (App.Current.MainWindow.DataContext is IConfigureService service)
                {
                    service.Configure();
                }
                base.OnInitialized();
            });
        }

        protected override void OnStartup(StartupEventArgs e)
        {   
            string logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }

            // Configure log4net
            log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));



            bool isOwned;
            string mutexName = "Global\\QuanYiPlaceOrderAdmin";

            mutex = new Mutex(true, mutexName, out isOwned);

            if (!isOwned)
            {
                log.Warn("Another instance of the application is already running.");
                Growl.ErrorGlobal("已开启管理端,请关闭");
                Application.Current.Shutdown();
                return;
            }

            AppLog.WriteInfo("管理端程序启动");
            base.OnStartup(e);
        }


        protected override void OnExit(ExitEventArgs e)
        {
            log.Info("Application exited");
            HandyControl.Controls.MessageBox.Show("有另一管理端程序正在运行，请检查！", "提示");
            mutex?.ReleaseMutex();
            base.OnExit(e);
        }
    }

}
